import { type Component, createSignal, mergeProps, splitProps } from "solid-js";
import type { RouteDefinition } from "@solidjs/router";
import type { JSX } from "solid-js/jsx-runtime";
import TextBox from "@lib/TextBox";
import BsButton from "@lib/Button";
import { FcInput, FormItemFloating } from "@lib/FormControl";
import FcFormItem from "@lib/form/FcFormItem";
import type { template } from "solid-js/web";
import { FormControl, FormField, type ValueAccessor } from "solid-form-context";
import type { FcFormItemLayoutConfig } from "@lib/form/FcFormItemLayout/types";
import FcForm from "@lib/form/FcForm";
import FcFormSubmit from "@lib/form/FcFormSubmit";
import type { FcListContext } from "@lib/FormControl/List/types";
import FcList from "@lib/FormControl/List";
import { logger } from "@lib/utils";

const Input: Component<
  Omit<JSX.InputHTMLAttributes<HTMLInputElement>, "value" | "onChange"> &
    ValueAccessor<any>
> = (props) => {
  const [local, restProps] = splitProps(mergeProps({ type: "text" }, props), [
    "value",
    "onValueChanged",
  ]);
  return (
    <input
      {...restProps}
      value={local.value}
      onInput={(e) => local.onValueChanged?.(e.currentTarget.value)}
    ></input>
  );
};

const horizontalTemplate: FcFormItemLayoutConfig["template"] = ({
  label,
  field,
  classList,
}) => {
  return (
    <div class="row mb-3" classList={classList}>
      <label class="col-sm-2 col-form-label">{label}</label>
      <div class="col-sm-10">{field}</div>
    </div>
  );
};

interface House {
  address: string;
}

interface Person {
  id?: number;
  name?: string;
}

const FormDemo: Component = () => {
  const [value, setValue] = createSignal({
    id: 1,
    name: "x",
  });

  const [persons, setPersons] = createSignal<Person[]>([]);

  const [listInstance, setListInstance] = createSignal<
    FcListContext | undefined
  >(undefined);

  const handleSubmit = (values: any) => {
    console.log("submit!", values);
  };

  const clear = () => listInstance()?.clearAll();

  const add = () => {
    listInstance()?.append("");
  };

  const remove = (index: number) => {
    listInstance()?.removeAt(index);
  };

  const [obj, setObj] = createSignal({ id: "1" });
  const [inputValue, setInputValue] = createSignal("");

  const outputValue = (name: string) => (v: any) => logger.log(name, v);

  return (
    <div>
      <div>
        <h1>Nested Form</h1>
        <FcForm
          value={{}}
          onSubmit={(v) => console.log("nested form submited!", v)}
        >
          <FcFormItem
            name={"id"}
            label={"Id"}
            control={FcInput}
            controlProps={{ classList: ["mb-3"] }}
            onValueChanged={outputValue("id")}
          ></FcFormItem>

          <FcFormItem
            name={"address"}
            label={"address"}
            onValueChanged={outputValue("address")}
          >
            <FormControl
              control={TextBox}
              onControlValueChanged={{
                eventName: "onChange",
                generateHandler: (setter) => (v) => setter?.(v),
              }}
              controlProps={{
                disabled: true,
                classList: { disabled: true },
              }}
            ></FormControl>
          </FcFormItem>

          <FcFormItem
            name={"address"}
            label={"address-1"}
            control={FcInput}
            controlProps={{
              disabled: true,
              classList: { disabled: true },
            }}
          ></FcFormItem>

          <FcFormItem
            name={"detail"}
            label={"detail"}
            onValueChanged={outputValue("detail")}
          >
            <FcFormItem
              name={"address"}
              label={"address"}
              onValueChanged={outputValue("detail.address")}
            >
              {/* <FormControl
                control={TextBox}
                onControlValueChanged={{
                  eventName: "onChange",
                  generateHandler: (setter) => (v) => setter?.(v),
                }}
              ></FormControl> */}
              <FormControl control={FcInput} controlProps={{}}></FormControl>
            </FcFormItem>
          </FcFormItem>

          <FcFormItem
            name={"items"}
            isArray
            label={"Items"}
            onValueChanged={outputValue("items")}
          >
            <div>
              <FormControl
                control={FcList}
                controlProps={{
                  onRef: (ref) => {
                    setListInstance(ref);
                  },
                  children: (item, index, ctx) => (
                    <FormField name={index}>
                      <div>
                        <FormControl
                          control={"input"}
                          controlProps={{ placeholder: `index-${index}` }}
                          onControlValueChanged={{
                            eventName: "oninput",
                            generateHandler: (setter) => (e) =>
                              setter?.(e.target.value),
                          }}
                        ></FormControl>
                        <button
                          type="button"
                          class="btn btn-sm btn-danger"
                          onclick={() => ctx.removeAt(index)}
                        >
                          remove
                        </button>
                      </div>
                    </FormField>
                  ),
                }}
              ></FormControl>
            </div>
            <div class="d-flex grid gap-1">
              <button
                type="button"
                class="btn btn-sm btn-primary"
                onclick={add}
              >
                add
              </button>

              <button
                type="button"
                class="btn btn-sm btn-warning"
                onclick={clear}
              >
                clear
              </button>
            </div>
          </FcFormItem>

          <FcFormSubmit></FcFormSubmit>
        </FcForm>
      </div>
    </div>
  );
};

export const FormDemoRoute: RouteDefinition = {
  path: "/form",
  component: FormDemo,
};

export default FormDemo;
